package com.bookstore.dao;

import com.bookstore.utils.JdbcUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public abstract class BaseDao {
    QueryRunner queryRunner = new QueryRunner();

    public int update(String sql,Object... args){
        int result=-1;
        Connection connection = JdbcUtil.getConnection();
        try {
            result = queryRunner.update(connection, sql, args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JdbcUtil.closeConnection(connection);
        }
        return result;
    }

    public <T>List<T> queryMore(Class<T> type,String sql,Object... args){
        Connection connection = JdbcUtil.getConnection();
        try {
            return queryRunner.query(connection,sql,args,new BeanListHandler<T>(type));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JdbcUtil.closeConnection(connection);
        }
        return null;
    }

    public <T> T queryOne(Class<T> type,String sql,Object... args){
        Connection connection = JdbcUtil.getConnection();
        try {
            return queryRunner.query(connection,sql,args,new BeanHandler<T>(type));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JdbcUtil.closeConnection(connection);
        }
        return null;
    }

    public Object queryItem(String sql,Object... args){
        Connection connection = JdbcUtil.getConnection();
        try {
            return queryRunner.query(connection,sql,new ScalarHandler(),args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JdbcUtil.closeConnection(connection);
        }
        return null;
    }
}
